package com.wbao.dianniu.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.Mode;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.OnRefreshListener;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.AnonymousAdapter;
import com.wbao.dianniu.customView.ClearEditText;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.im.AddFriendActivity;
import com.wbao.dianniu.listener.IQaListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.update.AmDataChangeManager;
import com.wbao.dianniu.update.AmDataChangeManager.IAmDataListener;
import com.wbao.dianniu.manager.QaManager;
import com.wbao.dianniu.utils.Utils;

import java.util.List;

/**
 * 问答搜索
 *
 * @author yejianjun
 */
public class AmSearchActivity extends Activity implements IQaListener, IAmDataListener, View.OnClickListener {

    private PullToRefreshListView mListView;
    private ClearEditText clearEditText;
    private AnonymousAdapter adapter;
    private final int PAGE_COUNTS = 10;
    private QaManager manager;
    private ListView actualListView;
    private String searchContent;
    private LinearLayout noDataLayout;
    private ImageView backIV;
    private Button cancelBtn;
    private TextView addFriend, jobTV, recruitTV, actTV, nearTV;
    private TextView noDataTV;
    private AmDataChangeManager amDataChangeManager;
    //是否重新搜索
//    private boolean isNewSearch = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 系统版本大于19
            Utils.setTranslucentStatus(this, true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
        }
        setContentView(R.layout.activity_qa_search);
        initView();
        initBaseView();
    }

    private void initView() {
        cancelBtn = (Button) findViewById(R.id.title_search_cancel);
        cancelBtn.setOnClickListener(this);
        backIV = (ImageView) findViewById(R.id.title_search_back);
        backIV.setOnClickListener(this);
        // 先屏蔽返回按钮
        backIV.setVisibility(View.GONE);
        clearEditText = (ClearEditText) findViewById(R.id.title_search_clearET);
        noDataLayout = (LinearLayout) findViewById(R.id.search_nodata_layout);
        noDataLayout.setVisibility(View.VISIBLE);
        noDataTV = (TextView) findViewById(R.id.no_data_tv);

        adapter = new AnonymousAdapter(this, 2);
        mListView = (PullToRefreshListView) findViewById(R.id.search_qa_listview);
        mListView.setMode(Mode.PULL_UP_TO_REFRESH);
        mListView.setOnRefreshListener(onRefreshListener);

        actualListView = mListView.getRefreshableView();
        registerForContextMenu(actualListView);
        actualListView.setAdapter(adapter);
        actualListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                Utils.intoAmDetailActivity(AmSearchActivity.this, (QaResponse) adapter.getItem(position - 1));
            }
        });
        clearEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String content = clearEditText.getText().toString().trim();
                    if (TextUtils.isEmpty(content)) {
                        return false;
                    }
                    adapter.cleanData();
                    searchContent = clearEditText.getText().toString().trim();
                    requstData(searchContent, "down");
                    return true;
                }
                return false;
            }
        });

        manager = new QaManager(this);
        manager.addQaListener(this);
        amDataChangeManager = AmDataChangeManager.getInstance();
        amDataChangeManager.addAmChangeListener(this);
    }

    private void initBaseView() {
        addFriend = (TextView) findViewById(R.id.other_include_friend);
        jobTV = (TextView) findViewById(R.id.other_include_job);
        recruitTV = (TextView) findViewById(R.id.other_include_recruit);
        actTV = (TextView) findViewById(R.id.other_include_act);
        nearTV = (TextView) findViewById(R.id.other_include_near);
        addFriend.setOnClickListener(this);
        jobTV.setOnClickListener(this);
        recruitTV.setOnClickListener(this);
        actTV.setOnClickListener(this);
        nearTV.setOnClickListener(this);
    }

    OnRefreshListener onRefreshListener = new OnRefreshListener() {

        @Override
        public void onRefresh() {
            //  上拉刷新 加载请求数据
            pullUpRequest();
        }
    };

    // 上拉刷新数据请求
    private void pullUpRequest() {
        // 没有搜索结果 或者数据为空 上拉没有效果
        requstData(searchContent, "up");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeQaListener(this);
        }
        if(null != amDataChangeManager)
            amDataChangeManager.removeAmChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        /*case R.id.search_imagebutton01:
            Utils.hideSoftInput(AmSearchActivity.this, clearEditText);
			String content = clearEditText.getText().toString().trim();
			if (TextUtils.isEmpty(content)) {
				return;
			}
			adapter.cleanData();
			searchContent = clearEditText.getText().toString().trim();
			currentPage = 1;
			requstData(searchContent, currentPage);
			break;*/
            case R.id.other_include_friend:
                intent(AddFriendActivity.class);
                break;
            case R.id.other_include_job:
                intent(ComRecruitActivity.class);
                break;
            case R.id.other_include_recruit:
                intent(JobListActivity.class);
                break;
            case R.id.other_include_act:
                Intent offline_intent = new Intent();
                offline_intent.putExtra(Const.BUNDLE_DATA, "");
                offline_intent.setClass(this, OfflineActivity.class);
                startActivity(offline_intent);
                break;
            case R.id.other_include_near:
                intent(KnowListActivity.class);
                break;
            case R.id.title_search_back:
            case R.id.title_search_cancel:
                this.finish();
                break;
            default:
                break;
        }

    }

    private void intent(Class cls) {
        Intent intent = new Intent();
        intent.setClass(AmSearchActivity.this, cls);
        startActivity(intent);
    }

    OnItemClickListener itemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            //intent put extra
            Intent contentIntent = new Intent();
            Bundle bundle = new Bundle();
            QaResponse resp = (QaResponse) adapter.getItem(position - 1);
            if (0 == resp.showAliasName) {
                bundle.putString(Const.BUNDLE_REALNAME, "");
            } else {
                bundle.putString(Const.BUNDLE_REALNAME, resp.realName);
            }
            bundle.putInt(Const.BUNDLE_ISGOOD, resp.isGood);
            bundle.putString(Const.BUNDLE_CONTENT, resp.content);
            bundle.putInt(Const.BUNDLE_VISITORCOUNT, resp.visitorCount);
            bundle.putInt(Const.BUNDLE_FORWARDCOUNT, resp.forwardCount);
            bundle.putInt(Const.BUNDLE_GOODCOUNT, resp.goodCount);
            bundle.putInt(Const.BUNDLE_ANSWERCOUNT, resp.answerCount);
            bundle.putInt(Const.BUNDLE_ACCOUNTID, resp.accountId);
            bundle.putInt(Const.BUNDLE_QUESTID, resp.id);
            bundle.putString(Const.BUNDLE_QUESTIMGS, resp.questImgs);
            contentIntent.putExtra(Const.AM_DATA_BUNDLE, bundle);
            contentIntent.setClass(AmSearchActivity.this, AmDetailActivity.class);
            AmSearchActivity.this.startActivity(contentIntent);

        }
    };

    private void requstData(String content, String refresh) {
        if (TextUtils.isEmpty(content)) {
            return;
        }
        manager.reqData(GlobalContext.getAccountId(), content, 2, 0, PAGE_COUNTS, adapter.getLastId(), refresh);
    }

    @Override
    public void onQaFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub
        mListView.onRefreshComplete(false, true);
    }

    @Override
    public void onQaSuccess(List<QaResponse> list) {
        // TODO Auto-generated method stub
        mListView.onRefreshComplete(false, true);
        noDataLayout.setVisibility(View.GONE);
        backIV.setVisibility(View.VISIBLE);
        //收到数据
        if (null != list) {
            adapter.addBackwardList(list);
            if (0 == adapter.getCount()) {
                noDataTV.setVisibility(View.VISIBLE);
                mListView.setVisibility(View.GONE);
            } else {
                Utils.hideSoftInput(AmSearchActivity.this, clearEditText);
                noDataTV.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
            }
            adapter.notifyDataSetChanged();
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void addOneData(QaResponse addData) {
        // TODO Auto-generated method stub
        noDataLayout.setVisibility(View.GONE);
        adapter.addOneQuestData(addData);
    }

    @Override
    public void removeOneData(int questId) {
        // TODO Auto-generated method stub
        adapter.removeOneData(questId);
        if (adapter.getCount() == 0) {
            noDataTV.setVisibility(View.VISIBLE);
        } else {
            noDataTV.setVisibility(View.GONE);
        }
    }

    @Override
    public void priseNotify(int questId, int isGood, int goodCounts) {
        // TODO Auto-generated method stub
        adapter.priseNotify(questId, isGood, goodCounts);
    }

    @Override
    public void replyNotify(int questId, int answerCounts) {
        // TODO Auto-generated method stub
        adapter.replyNotify(questId, answerCounts);
    }

    @Override
    public void updateVisitor(int questId, int visitorCounts) {
        adapter.updateVisitor(questId,visitorCounts);
    }

}
